package com.huike.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.dto.TbBusinessPageDTO;
import com.huike.business.domain.vo.TbBusinessVO;
import com.huike.business.service.TbBusinessService;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.TbRulePool;
import com.huike.clues.domain.vo.AssignmentVo;
import com.huike.clues.mapper.SysUserMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;

import com.huike.clues.mapper.TbRulePoolMapper;
import com.huike.common.constant.ErrorMessageConstants;
import com.huike.common.core.domain.entity.SysUserDTO;
import com.huike.common.exception.BaseException;
import com.huike.common.utils.SecurityUtils;

import lombok.RequiredArgsConstructor;
import com.huike.common.constant.HttpStatus;
import com.huike.common.core.page.TableDataInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * @author 93238
 * @description 针对表【tb_business(商机)】的数据库操作Service实现
 * @createDate 2023-10-12 06:08:37
 */
@RequiredArgsConstructor
@Service
public class TbBusinessServiceImpl extends ServiceImpl<TbBusinessMapper, TbBusiness> implements TbBusinessService {

    private final TbClueMapper tbClueMapper;

    private final SysUserMapper sysUserMapper;

    private final TbAssignRecordMapper tbAssignRecordMapper;
    private final TbRulePoolMapper tbRulePoolMapper;


    /**
     * 线索转商机
     *
     * @param clueId 线索id
     */
    @Override
    @Transactional
    public void changeBusiness(Long clueId) {
        // 查询线索判断是否存在
        TbClue clue = tbClueMapper.selectById(clueId);
        if (clue == null) {
            throw new BaseException(ErrorMessageConstants.CLUE_DOES_NOT_EXIST);
        }

        // 新增商机
        TbBusiness business =
                TbBusiness.builder().name(clue.getName()).phone(clue.getPhone()).channel(clue.getChannel()).activityId(clue.getActivityId()).sex(clue.getSex()).age(clue.getAge()).weixin(clue.getWeixin()).qq(clue.getQq()).level(clue.getLevel()).subject(clue.getSubject()).createBy(SecurityUtils.getUsername()).status("1").lastUpdateTime(new Date()).clueId(clueId).transfer("0").build();
        if (!save(business)) {
            throw new BaseException(ErrorMessageConstants.FAILED_TO_ADD_BUSYNESS);
        }

        // 分配商机，默认给管理员
        SysUserDTO admin = sysUserMapper.selectUserByUserName("admin");
        if (tbAssignRecordMapper.insert(TbAssignRecord.builder().assignId(business.getId()).userId(admin.getUserId()).userName(admin.getUserName()).deptId(admin.getDeptId()).createTime(new Date()).createBy(SecurityUtils.getUsername()).latest("1").type("1").build()) != 1) {
            throw new BaseException(ErrorMessageConstants.FAILED_TO_ALLOCATE_BUSYNESS);
        }

        // 修改线索
        clue.setEndTime(new Date());
        if (tbClueMapper.updateById(clue) != 1) {
            throw new BaseException(ErrorMessageConstants.FAILED_TO_UPDATE_CLUE);
        }

    }

    private final TbBusinessMapper tbBusinessMapper;

    /**
     * 查询商机列表
     *
     * @param tbBusinessPageDTO
     * @return
     */
    @Override
    public TableDataInfo<List<TbBusinessVO>> pageList(TbBusinessPageDTO tbBusinessPageDTO) {
        PageHelper.startPage(tbBusinessPageDTO.getPageNum(), tbBusinessPageDTO.getPageSize());
        Page<TbBusinessVO> tbBusinessVOS = tbBusinessMapper.findByCondition(tbBusinessPageDTO);
        // 封装数据
        TableDataInfo<List<TbBusinessVO>> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setRows(tbBusinessVOS.getResult());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(tbBusinessVOS.getTotal());
        // 数据返回
        return tableDataInfo;
    }

    /**
     * 新增商机
     *
     * @param tbBusiness
     */
    @Override
    // @AutoFill(FillType.CREATE)
    @Transactional(rollbackFor = Exception.class)
    public void add(TbBusiness tbBusiness) {
        // 补全数据
        tbBusiness.setActivityId(null);
        tbBusiness.setLevel("0");
        tbBusiness.setCourseId(null);
        tbBusiness.setCreateBy(SecurityUtils.getUsername());
        tbBusiness.setCreateTime(new Date());
        tbBusiness.setStatus("1");
        tbBusiness.setLastUpdateTime(new Date());
        tbBusiness.setTransfer("0");
        tbBusiness.setActivityId(35L);// 默认添加时的活动id是35
        tbBusinessMapper.insert(tbBusiness);

        // 默认新增商机由管理员跟进
        SysUserDTO admin = sysUserMapper.selectUserByUserName("admin");
        tbAssignRecordMapper.insert(TbAssignRecord.builder().userName(admin.getUserName()).assignId(tbBusiness.getId()).userId(admin.getUserId()).deptId(admin.getDeptId()).createTime(new Date()).createBy(SecurityUtils.getUsername()).latest("1").type("1").build());

    }

    /**
     * 获取商机详细信息
     *
     * @param id
     * @return
     */
    @Override
    public TbBusinessVO findById(Long id) {
        // 将id封装到dto
        TbBusinessPageDTO tbBusinessPageDTO = new TbBusinessPageDTO();
        tbBusinessPageDTO.setId(id);
        // 利用分页查询查找
        Page<TbBusinessVO> businessVOS = tbBusinessMapper.findByCondition(tbBusinessPageDTO);
        // 获取查找到的对象并且返回
        return businessVOS.get(0);
    }

    /**
     * 商机分配
     *
     * @param assignmentVo
     */
    @Override
    public void assignment(AssignmentVo assignmentVo) {
        // 判断用户是否存在
        SysUserDTO user = sysUserMapper.selectUserById(assignmentVo.getUserId());
        if (user == null) {
            throw new BaseException(ErrorMessageConstants.USER_DOES_NOT_EXIST);
        }

        // 判断商机是否存在
        LambdaQueryWrapper<TbBusiness> wrapper = new LambdaQueryWrapper<TbBusiness>();
        wrapper.in(TbBusiness::getId, assignmentVo.getIds());
        int count = count(wrapper);
        if (count != assignmentVo.getIds().length) {
            throw new BaseException(ErrorMessageConstants.BUSINESS_DOES_NOT_EXIST);
        }

        // 判断是否达到商机保有量上限
        LambdaQueryWrapper<TbAssignRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TbAssignRecord::getUserId, assignmentVo.getUserId());
        lqw.eq(TbAssignRecord::getType, "1");
        Integer sum = tbAssignRecordMapper.selectCount(lqw);
        LambdaQueryWrapper<TbRulePool> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(TbRulePool::getType, "1");
        if (sum.equals(tbRulePoolMapper.selectOne(wrapper1).getMaxNunmber())) {
            throw new BaseException(ErrorMessageConstants.HOLDING_TOO_MANY_BUSINESS);
        } else {
            // 判断都没有问题就插入数据到跟进记录表，如果用户的保有量在插入过程中达到最大值就无法继续插入
            SysUserDTO user1 = sysUserMapper.selectUserById(assignmentVo.getUserId());
            TbAssignRecord assignRecord =
                    TbAssignRecord.builder().userId(assignmentVo.getUserId()).userName(user1.getUserName()).deptId(user1.getDeptId()).createTime(new Date()).createBy(SecurityUtils.getUsername()).latest("1").type("1").build();
            int index = 0;// 方便在增强for里面获取索引
            for (Long businessId : assignmentVo.getIds()) {
                assignRecord.setAssignId(businessId);
                // 将同一条商机的least改为0
                TbAssignRecord tbAssignRecord = TbAssignRecord.builder().latest("0").build();
                LambdaQueryWrapper<TbAssignRecord> wrapper3 = new LambdaQueryWrapper<>();
                wrapper3.eq(TbAssignRecord::getAssignId, businessId);
                tbAssignRecordMapper.update(tbAssignRecord, wrapper3);
                // 插入新的分配记录
                tbAssignRecordMapper.insert(assignRecord);
                // 插入成功后就改变商机的状态为：“跟进中”
                TbBusiness tbBusiness = TbBusiness.builder().status("1").lastUpdateTime(new Date()).build();
                QueryWrapper<TbBusiness> wrapper2 = new QueryWrapper<>();
                tbBusinessMapper.update(tbBusiness, wrapper2);
                sum++;
                index++;// 索引+1记录成功条数
                if (sum.equals(tbRulePoolMapper.selectOne(wrapper1).getMaxNunmber())) {
                    throw new BaseException(index + "条操作成功，" + (assignmentVo.getIds().length - index) +
                            "条操作失败，商机保有量已达到上限！");
                }
            }
        }
    }

    /**
     * 修改商机
     *
     * @param tbBusinessVO // TODO 未找到测试接口，待完善，待测试
     */
    @Override
    public void updateBusiness(TbBusinessVO tbBusinessVO) {
        // 更新条件
        LambdaQueryWrapper<TbBusiness> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbBusiness::getId, tbBusinessVO.getId());
        TbBusiness tbBusiness = TbBusiness.builder().build();
        BeanUtils.copyProperties(tbBusinessVO, tbBusiness);
        // 补全最近更新时间
        tbBusiness.setLastUpdateTime(new Date());
        // 更新商机
        tbBusinessMapper.update(tbBusiness, wrapper);
    }

    /**
     * 踢回公海
     *
     * @param id
     * @param reason
     */
    @Override
    public void back(Long id, String reason) {
        // TODO 退回公海原因暂时不知道更新哪里，退回公海统计次数加1
        // 更新数据库中对应的数据
        TbBusiness tbBusiness = TbBusiness.builder().lastUpdateTime(new Date()).endTime(new Date()).status("3").build();
        LambdaQueryWrapper<TbBusiness> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbBusiness::getId, id);
        tbBusinessMapper.update(tbBusiness,wrapper);
    }

    /**
     * 批量捞取
     * @param assignmentVo
     */
    @Override
    public void gain(AssignmentVo assignmentVo) {
        assignment(assignmentVo);
    }

    /**
     * 分页查找公海池
     * @param tbBusinessPageDTO
     * @return
     */
    @Override
    public TableDataInfo<List<TbBusinessVO>> poolList(TbBusinessPageDTO tbBusinessPageDTO) {
        PageHelper.startPage(tbBusinessPageDTO.getPageNum(), tbBusinessPageDTO.getPageSize());
        Page<TbBusinessVO> tbBusinessVOS = tbBusinessMapper.findPoolByCondition(tbBusinessPageDTO);
        // 封装数据
        TableDataInfo<List<TbBusinessVO>> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setRows(tbBusinessVOS.getResult());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(tbBusinessVOS.getTotal());
        // 数据返回
        return tableDataInfo;
    }

    /**
     * 删除商机
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        List<TbBusiness> tbBusinesses = tbBusinessMapper.selectBatchIds(ids);
        for (TbBusiness tbBusiness : tbBusinesses) {
            if (!tbBusiness.getStatus().equals("3")){
                throw new BaseException(ErrorMessageConstants.FAILED_TO_BATCH_DELETE_BUSINESS);
            }
        }
        //批量删除
        delete(ids);
    }
}




